<template>
  <div>
    <div class="search">
      <el-select placeholder="请选择维修类型查询" style="width: 200px; margin-right: 10px" v-model="repairType">
        <el-option v-for="item in repairTypeList" :key="item.id" :value="item.type"></el-option>
      </el-select>
      <el-select placeholder="请选择维修状态查询" style="width: 200px; margin-right: 10px" v-model="repairStatus">
        <el-option v-for="item in statusList" :key="item.id" :value="item.type"></el-option>
      </el-select>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="table">
      <el-table :data="repair" strip @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="序号" width="70" align="center" sortable></el-table-column>
        <el-table-column prop="repairNumber" label="报修单号"></el-table-column>
        <el-table-column prop="buildingNumber" label="楼号"></el-table-column>
        <el-table-column prop="repairAddress" label="报修地址"></el-table-column>
        <el-table-column prop="reporter" label="报修人"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
        <el-table-column label="报修信息">
          <template v-slot="scope">
            <el-button size="mini" type="info" plain @click="viewRepairInfo(scope.row)">详情</el-button>
          </template>
        </el-table-column>
        <el-table-column label="维修信息">
          <template v-slot="scope">
            <el-button size="mini" type="info" plain @click="editRepairDetails(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
        <el-table-column label="评价">
          <template v-slot="scope">
            <el-button size="mini" type="success" plain @click="viewEvaluation(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 报修信息对话框 -->
    <el-dialog title="报修信息" :visible.sync="repairInfoVisible" :width="isMobile ? '90%' : '40%'"
    class="dialog-mobile-adapted">
      <el-form :model="repairInfo" label-width="100px">
        <el-form-item label="类型">
          <el-input v-model="repairInfo.repairType" readonly></el-input>
        </el-form-item>
        <el-form-item label="报修内容">
          <el-input v-model="repairInfo.repairContent" type="textarea" readonly></el-input>
        </el-form-item>
        <el-form-item label="报修图像">
          <el-image v-for="img in repairInfo.reportImages" :src="img" :key="img" style="margin: 5px" />
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 新增/编辑弹窗 -->
    <el-dialog title="新增/编辑信息" :visible.sync="repairDetailsVisible" :width="isMobile ? '90%' : '40%'"
    class="dialog-mobile-adapted">
      <el-form :model="repairDetails" label-width="120px" ref="repairDetailsForm">
        <el-form-item label="维修员1">
          <el-input v-model="repairDetails.repairPerson1"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="repairDetails.repairPerson1Phone"></el-input>
        </el-form-item>
        <el-form-item label="维修员2">
          <el-input v-model="repairDetails.repairPerson2"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="repairDetails.repairPerson2Phone"></el-input>
        </el-form-item>
        <el-form-item label="现有维修图像">
          <!-- <el-image v-if="repairInfo.image" :src="repairInfo.image" style="width: 100%;"></el-image> -->
          <el-image v-for="img in repairDetails.repairImages" :src="img" :key="img" style="margin: 5px" />
        </el-form-item>
        <el-form-item label="维修图像">
          <el-upload
            class="avatar-uploader"
            :action="$baseUrl + '/files/upload'"
            :headers="{ token: user.token }"
            list-type="picture"
            :on-success="handleAvatarSuccess"
          >
            <el-button type="primary">上传维修图像</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="repairDetailsVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRepairDetails">保存</el-button>
      </div>
    </el-dialog>
  
    
    <!-- 评价查看对话框 -->
    <el-dialog title="评价" :visible.sync="evaluationVisible" :width="isMobile ? '90%' : '40%'"
    class="dialog-mobile-adapted">
      <el-form :model="evaluationForm" label-width="100px">
        <el-form-item label="评分">
          <el-rate v-model="evaluationForm.rating" disabled></el-rate>
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input v-model="evaluationForm.comments" type="textarea" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="evaluationVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Admin",
  data() {
    return {
      repair: [
        {
          id: 1,
          repairNumber: '12345',
          buildingNumber: 'A1',
          repairAddress: '某某地址',
          reporter: '张三',
          contactPhone: '123456789',
          repairType: '电路问题',
          repairContent: '电路短路需要维修',
          repairStatus:'已分配',
          repairPerson1:'维修员A',
          repairPerson1Phone:'111111',
          repairPerson2:'维修员B',
          repairPerson2Phone:'22222',
          rating:0,
          comments: '', 
          pictures:[],         
          reportImages: [
            'http://localhost:9090/files/1733649497371-1733648955008-用例图.jpg',
            'http://localhost:9090/files/1733649497371-1733648955008-用例图.jpg',
          ],
          repairImages: [
            'http://example.com/uploads/image1.jpg',
            'http://example.com/uploads/image1.jpg',
          ],
        },
      ],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 1,
      repairType: null,
      repairStatus: null,
      fromVisible: false,
      repairInfoVisible: false,
      repairInfo: {},
      repairDetailsVisible: false,
      repairDetails: {
        pictures:[]
      },
      evaluationVisible: false,
      evaluationForm: {
        rating: 0,
        comments: ''
      },
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      ids: [],
      rules:{}
    }
  },
  computed: {
    isMobile() {
      return window.innerWidth < 768;
    },
  },
  created() {
    this.load(1);
    this.fetchRepairTypes();
    this.fetchStatuses();
  },
  methods: {
    fetchRepairTypes() {
      this.$request.get('/category/selectAll').then(res => {
        this.repairTypeList = res.data || [];
      });
    },
    fetchStatuses() {
      this.$request.get('/state/selectAll').then(res => {
        this.statusList = res.data || [];
      });
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? '/worker/repair/update' : '/worker/repair/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    saveRepairDetails() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.repairDetailsForm.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.repairDetails.id ? '/worker/repair/update' : '/worker/repair/add',
            method: this.repairDetails.id ? 'PUT' : 'POST',
            data: this.repairDetails
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.repairDetailsVisible = false
              this.load(1)
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    load(pageNum) {
      this.pageNum = pageNum;
      this.$request.get('/worker/repair/selectPage', {
        params: { pageNum, pageSize: this.pageSize, repairType: this.repairType, repairStatus: this.repairStatus, },
      }).then(res => {
        this.repair = res.data?.list || [];
        this.total = res.data?.total || 0;
      });
    },
    reset() {
      this.repairType = null;
      this.repairStatus = null;
      this.load(1);
    },
    editRepairDetails(row) {
      this.repairDetails = {
        // ...row.repairDetails,
        // pictures: row.repairImages || '',
        ...row
      };
      this.repairDetailsVisible = true;
    },
    viewRepairInfo(row) {
      this.repairInfo = { ...row };
      this.repairInfoVisible = true;
    },
    viewEvaluation(row) {
      this.evaluationForm = {
        rating: row.rating || 0,
        comments: row.comments || '暂无评价',
      };
      this.evaluationVisible = true;
    },
    handleSelectionChange(rows) {
      this.ids = rows.map(v => v.id); // 获取选中项的 ID
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum);
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把头像属性换成上传的图片的链接
      if (Array.isArray(this.repairDetails.pictures)) {
        this.repairDetails.pictures.push(response.data);
      } else {
        console.error('this.form.picture is not an array!');
        // 你可能需要在这里重置this.form.picture为一个数组
        this.repairDetails.pictures = [response.data]; // 或者根据需要处理
      }
    },
  }
}
</script>

<style scoped>
/* 手机端表格滚动 */
@media (max-width: 767px) {
  .table {
    overflow-x: auto;
  }
}

/* 弹窗适配 */
.dialog-mobile-adapted .el-dialog__body {
  padding: 15px;
}
</style>